package serializable.jdk;

import serializable.User;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.nio.ByteBuffer;


public class Test2 {

    private static User user = null;

    public static void main(String[] args) throws IOException {

        user = new User();
        user.setName("luobinjie");
        user.setCreed("I Can!");
        user.setAge(18);

        loopUseJDKSerializable();
        loopUseByteBuffer();

        /*
            user没有age前：
         * jdk time : 1634ms
         * bytebuffer time : 1015ms
           user添加age后：
           jdk time : 2235ms
            bytebuffer time : 1587ms
         */
    }

    private static void loopUseJDKSerializable() throws IOException {
        long startTime = System.currentTimeMillis();
        for (int i=0; i<1000000; i++)
            useJDKSerializable();
        long endTime = System.currentTimeMillis();
        System.out.println("jdk time : " + (endTime-startTime) + "ms");
    }

    private static void loopUseByteBuffer() throws IOException {
        long startTime = System.currentTimeMillis();
        for (int i=0; i<1000000; i++)
            useJDKSerializable();
        long endTime = System.currentTimeMillis();
        System.out.println("bytebuffer time : " + (endTime-startTime) + "ms");
    }






        /**
         * jdk序列化示例
         */
    private static void useJDKSerializable() throws IOException {

        ByteArrayOutputStream bos = new ByteArrayOutputStream();
        ObjectOutputStream oos = new ObjectOutputStream(bos);
        oos.writeObject(user);
        bos.flush();
        oos.close();
        byte[] result = bos.toByteArray();
        bos.close();
    }



    private static void useByteBuffer(){

        ByteBuffer buffer = ByteBuffer.allocate(1024);
        byte[] nameValue = user.getName().getBytes();
        byte[] creedValue = user.getCreed().getBytes();
        buffer.putInt(nameValue.length);
        buffer.put(nameValue);
        buffer.putInt(creedValue.length);
        buffer.put(creedValue);
        buffer.putInt(user.getAge());
        buffer.flip();

        byte[] result = new byte[buffer.remaining()];
        buffer.get(result);
    }

}
